package com.chexiehui.jc.utils;

import com.blankj.utilcode.util.SPUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.entity.AuthInfo;
import com.chexiehui.jc.entity.UserInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;

/**
 * 不使用greenDao 直接使用SharedPreferences 来保存
 */
public class SerializableSpTools {

    public static void putAuthInfo(AuthInfo authInfo) {
        Gson gson = new Gson();
        Type type = new TypeToken<AuthInfo>() {
        }.getType();
        String json = gson.toJson(authInfo, type);
        SPUtils.getInstance(Constants.LOGIN_SCOPE).put(Constants.AUTH_INFO, json);
    }

    public static void clearAuthInfo() {
        SPUtils.getInstance(Constants.LOGIN_SCOPE).remove(Constants.AUTH_INFO, true);
    }

    public static AuthInfo getAuthInfo() {
        try {
            String json = SPUtils.getInstance(Constants.LOGIN_SCOPE)
                    .getString(Constants.AUTH_INFO);
            if (json == null || json.equals("")) {
                return new AuthInfo();
            }
            Gson gson = new Gson();
            Type type = new TypeToken<AuthInfo>() {
            }.getType();
            AuthInfo authInfo = gson.fromJson(json, type);
            return authInfo;
        } catch (Exception e) {
            return new AuthInfo();
        }
    }

    public static void putUserInfo(UserInfo userInfo) {
        Gson gson = new Gson();
        Type type = new TypeToken<UserInfo>() {
        }.getType();
        String json = gson.toJson(userInfo, type);
        SPUtils.getInstance(Constants.LOGIN_SCOPE).put(Constants.USER_INFO, json);
    }

    public static void clearUserInfo() {
        SPUtils.getInstance(Constants.LOGIN_SCOPE).remove(Constants.USER_INFO, true);
    }

    public static void clearLoginScope() {
        SPUtils.getInstance(Constants.LOGIN_SCOPE).clear(true);
    }

    public static UserInfo getUserInfo() {
        try {
            String json = SPUtils.getInstance(Constants.LOGIN_SCOPE)
                    .getString(Constants.USER_INFO);
            if (json == null || json.equals("")) {
                return new UserInfo();
            }
            Gson gson = new Gson();
            Type type = new TypeToken<UserInfo>() {
            }.getType();
            UserInfo userInfo = gson.fromJson(json, type);
            return userInfo;
        } catch (Exception e) {
            return new UserInfo();
        }
    }

    public static void setIsLogin(boolean value) {
        SPUtils.getInstance(Constants.LOGIN_SCOPE).put("islogin", value);
    }

    public static boolean isLogin() {
        return SPUtils.getInstance(Constants.LOGIN_SCOPE).getBoolean("islogin", false);
    }

}
